import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/vpn_provider.dart';
import '../providers/settings_provider.dart';
import '../models/server_config.dart';
import '../services/ip_location_service.dart';
import '../utils/formatters.dart';
import 'ping_test_dialog.dart';
import 'edit_server_dialog.dart';
import 'share_config_dialog.dart';

class ServerList extends StatelessWidget {
  final int? limit;
  final bool showGroupBadge; // 是否显示分组标签
  final bool onlyRecent; // 只显示有最近使用记录的服务器

  const ServerList({
    super.key,
    this.limit,
    this.showGroupBadge = false,
    this.onlyRecent = false,
  });

  @override
  Widget build(BuildContext context) {
    return Consumer<VpnProvider>(
      builder: (context, vpnProvider, _) {
        // Get already filtered and sorted servers from provider
        var servers = vpnProvider.servers.toList();

        // 如果只显示最近使用的，过滤掉没有 lastUsed 的服务器
        if (onlyRecent) {
          servers = servers.where((s) => s.lastUsed != null).toList();
        }

        // Apply pinned priority on top of provider's sorting
        // Pinned servers stay at top, keeping their relative order
        servers.sort((a, b) {
          if (a.isPinned && !b.isPinned) return -1;
          if (!a.isPinned && b.isPinned) return 1;
          return 0; // Keep provider's sorting for same pinned status
        });

        if (limit != null && servers.length > limit!) {
          servers = servers.sublist(0, limit!);
        }

        if (servers.isEmpty) {
          return Center(
            child: Padding(
              padding: const EdgeInsets.all(32),
              child: Column(
                children: [
                  Icon(
                    Icons.dns_outlined,
                    size: 64,
                    color: Colors.grey.shade400,
                  ),
                  const SizedBox(height: 16),
                  Text(
                    onlyRecent ? 'No recent servers' : 'No servers available',
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.grey.shade600,
                    ),
                  ),
                  if (onlyRecent) ...[
                    const SizedBox(height: 8),
                    Text(
                      'Connect to a server to see it here',
                      style: TextStyle(
                        fontSize: 13,
                        color: Colors.grey.shade500,
                      ),
                    ),
                  ],
                ],
              ),
            ),
          );
        }

        return ListView.builder(
          shrinkWrap: limit != null,
          physics: limit != null 
              ? const NeverScrollableScrollPhysics() 
              : const AlwaysScrollableScrollPhysics(),
          padding: limit != null ? EdgeInsets.zero : const EdgeInsets.all(16),
          itemCount: servers.length,
          itemBuilder: (context, index) {
            return ServerListItem(
              server: servers[index],
              showGroupBadge: showGroupBadge,
              index: index + 1, // 1-based index
            );
          },
        );
      },
    );
  }
}

class ServerListItem extends StatelessWidget {
  final ServerConfig server;
  final bool showGroupBadge;
  final int index; // 服务器序号

  const ServerListItem({
    super.key,
    required this.server,
    this.showGroupBadge = false,
    required this.index,
  });

  @override
  Widget build(BuildContext context) {
    return Consumer2<VpnProvider, SettingsProvider>(
      builder: (context, vpnProvider, settingsProvider, _) {
        // 使用组合ID进行严格的连接状态判断
        // 组合：基础ID + 分组 + 节点名称 + 备注
        final isCurrentServer = vpnProvider.status == VpnStatus.connected && 
                                server.matchesServer(vpnProvider.currentServer);
        final isTesting = vpnProvider.testingPingServerId == server.id;
        final showIndex = settingsProvider.showServerIndex;
        
        // 只在实际高亮时打印调试信息
        if (isCurrentServer) {
          print('✓ Connected Server Highlighted (Composite Match):');
          print('  Name: ${server.name}');
          print('  Group: ${server.group ?? "None"}');
          print('  Remarks: ${server.remarks ?? "None"}');
          print('  Base ID: ${server.id}');
          print('  Composite ID: ${server.getCompositeId()}');
          print('  Status: ${vpnProvider.status}');
        }
        
        final ipLocationService = IpLocationService();
        final countryFlag = server.countryCode != null 
            ? ipLocationService.getCountryFlag(server.countryCode!)
            : null;

        return AnimatedContainer(
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeInOut,
          margin: const EdgeInsets.only(bottom: 12),
          child: Card(
            margin: EdgeInsets.zero,
            elevation: isCurrentServer ? 12 : 2,
            shadowColor: isCurrentServer 
                ? Theme.of(context).colorScheme.primary.withOpacity(0.4)
                : Colors.black26,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16),
              side: isCurrentServer 
                  ? BorderSide(
                      color: Theme.of(context).colorScheme.primary,
                      width: 2,
                    )
                  : BorderSide(
                      color: Colors.grey.shade200,
                      width: 1,
                    ),
            ),
            child: Container(
              decoration: isCurrentServer
                  ? BoxDecoration(
                      borderRadius: BorderRadius.circular(16),
                      gradient: LinearGradient(
                        colors: [
                          Theme.of(context).colorScheme.primary.withOpacity(0.12),
                          Theme.of(context).colorScheme.primary.withOpacity(0.05),
                          Colors.transparent,
                        ],
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                        stops: const [0.0, 0.5, 1.0],
                      ),
                      // 添加内发光效果
                      boxShadow: [
                        BoxShadow(
                          color: Theme.of(context).colorScheme.primary.withOpacity(0.15),
                          blurRadius: 8,
                          spreadRadius: 0,
                          offset: const Offset(0, 2),
                        ),
                      ],
                    )
                  : null,
              child: ClipRRect(
                borderRadius: BorderRadius.circular(16),
                child: Stack(
                  children: [
                    // 添加顶部装饰条（仅连接时显示）
                    if (isCurrentServer)
                      Positioned(
                        top: 0,
                        left: 0,
                        right: 0,
                        child: Container(
                          height: 3,
                          decoration: BoxDecoration(
                            gradient: LinearGradient(
                              colors: [
                                Theme.of(context).colorScheme.primary,
                                Theme.of(context).colorScheme.primary.withOpacity(0.6),
                                Theme.of(context).colorScheme.primary,
                              ],
                              stops: const [0.0, 0.5, 1.0],
                            ),
                          ),
                        ),
                      ),
                    ListTile(
            contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            leading: Stack(
              children: [
                // 添加脉动效果的外圈（仅连接时）
                if (isCurrentServer)
                  Container(
                    width: 56,
                    height: 56,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border: Border.all(
                        color: Theme.of(context).colorScheme.primary.withOpacity(0.2),
                        width: 2,
                      ),
                    ),
                  ),
                Container(
                  width: 48,
                  height: 48,
                  decoration: isCurrentServer
                      ? BoxDecoration(
                          shape: BoxShape.circle,
                          gradient: LinearGradient(
                            colors: [
                              Theme.of(context).colorScheme.primary,
                              Theme.of(context).colorScheme.primary.withOpacity(0.8),
                            ],
                            begin: Alignment.topLeft,
                            end: Alignment.bottomRight,
                          ),
                          boxShadow: [
                            BoxShadow(
                              color: Theme.of(context).colorScheme.primary.withOpacity(0.4),
                              blurRadius: 8,
                              spreadRadius: 1,
                            ),
                          ],
                        )
                      : BoxDecoration(
                          shape: BoxShape.circle,
                          color: Colors.grey.shade300,
                        ),
                  child: Center(
                    child: showIndex
                        ? Text(
                            '$index',
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                              color: isCurrentServer ? Colors.white : Colors.grey.shade700,
                            ),
                          )
                        : countryFlag != null
                            ? Text(
                                countryFlag,
                                style: const TextStyle(fontSize: 24),
                              )
                            : Icon(
                                _getProtocolIcon(server.protocol),
                                color: isCurrentServer ? Colors.white : Colors.grey.shade700,
                                size: 22,
                              ),
                  ),
                ),
                // 协议标识小图标 (only show when not showing index and has country flag)
                if (countryFlag != null && !showIndex)
                  Positioned(
                    right: 4,
                    bottom: 4,
                    child: Container(
                      padding: const EdgeInsets.all(3),
                      decoration: BoxDecoration(
                        color: isCurrentServer
                            ? Colors.white
                            : Colors.grey.shade600,
                        shape: BoxShape.circle,
                        border: Border.all(
                          color: isCurrentServer
                              ? Theme.of(context).colorScheme.primary
                              : Colors.transparent,
                          width: 1.5,
                        ),
                      ),
                      child: Icon(
                        _getProtocolIcon(server.protocol),
                        color: isCurrentServer
                            ? Theme.of(context).colorScheme.primary
                            : Colors.white,
                        size: 10,
                      ),
                    ),
                  ),
                // 测试中指示器
                if (isTesting)
                  Positioned.fill(
                    child: Container(
                      decoration: BoxDecoration(
                        color: Colors.black.withOpacity(0.3),
                        shape: BoxShape.circle,
                      ),
                      child: const Center(
                        child: SizedBox(
                          width: 20,
                          height: 20,
                          child: CircularProgressIndicator(
                            strokeWidth: 2,
                            valueColor: AlwaysStoppedAnimation(Colors.white),
                          ),
                        ),
                      ),
                    ),
                  ),
              ],
            ),
        title: Row(
          children: [
            Expanded(
              child: Text(
                server.name,
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  color: isCurrentServer 
                      ? Theme.of(context).colorScheme.primary
                      : null,
                ),
              ),
            ),
            // 显示已连接标签 - 优化样式
            if (isCurrentServer)
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                margin: const EdgeInsets.only(right: 8),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [
                      Theme.of(context).colorScheme.primary,
                      Theme.of(context).colorScheme.primary.withOpacity(0.85),
                    ],
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                  ),
                  borderRadius: BorderRadius.circular(20),
                  boxShadow: [
                    BoxShadow(
                      color: Theme.of(context).colorScheme.primary.withOpacity(0.3),
                      blurRadius: 4,
                      offset: const Offset(0, 2),
                    ),
                  ],
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      width: 6,
                      height: 6,
                      decoration: BoxDecoration(
                        color: Colors.white,
                        shape: BoxShape.circle,
                        boxShadow: [
                          BoxShadow(
                            color: Colors.white.withOpacity(0.5),
                            blurRadius: 4,
                            spreadRadius: 1,
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(width: 6),
                    const Text(
                      'Connected',
                      style: TextStyle(
                        fontSize: 11,
                        fontWeight: FontWeight.w700,
                        color: Colors.white,
                        letterSpacing: 0.5,
                      ),
                    ),
                  ],
                ),
              ),
            // 显示分组标签
            if (showGroupBadge && server.group != null && server.group!.isNotEmpty)
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                decoration: BoxDecoration(
                  color: _getGroupColor(server.group!).withOpacity(0.2),
                  borderRadius: BorderRadius.circular(12),
                  border: Border.all(
                    color: _getGroupColor(server.group!).withOpacity(0.5),
                    width: 1,
                  ),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(
                      Icons.folder_outlined,
                      size: 12,
                      color: _getGroupColor(server.group!),
                    ),
                    const SizedBox(width: 4),
                    Text(
                      server.group!,
                      style: TextStyle(
                        fontSize: 11,
                        fontWeight: FontWeight.w600,
                        color: _getGroupColor(server.group!),
                      ),
                    ),
                  ],
                ),
              ),
          ],
        ),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 4),
            Row(
              children: [
                // 显示位置信息
                if (server.country != null) ...[
                  Icon(
                    Icons.location_on,
                    size: 14,
                    color: Colors.grey.shade600,
                  ),
                  const SizedBox(width: 4),
                  Expanded(
                    child: Text(
                      server.city != null 
                          ? '${server.city}, ${server.country}'
                          : server.country!,
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey.shade700,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ] else
                  Expanded(
                    child: Text('${server.address}:${server.port}'),
                  ),
              ],
            ),
            const SizedBox(height: 4),
            Row(
              children: [
                Icon(
                  Icons.speed,
                  size: 14,
                  color: getPingColor(server.ping),
                ),
                const SizedBox(width: 4),
                Text(
                  formatPing(server.ping),
                  style: TextStyle(
                    color: getPingColor(server.ping),
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(width: 12),
                // 显示地址信息（如果有位置信息）
                if (server.country != null) ...[
                  Icon(
                    Icons.dns,
                    size: 14,
                    color: Colors.grey.shade500,
                  ),
                  const SizedBox(width: 4),
                  Expanded(
                    child: Text(
                      '${server.address}:${server.port}',
                      style: TextStyle(
                        fontSize: 11,
                        color: Colors.grey.shade500,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ],
            ),
          ],
        ),
        trailing: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            if (server.isPinned)
              Icon(
                Icons.push_pin,
                color: Theme.of(context).colorScheme.primary,
                size: 20,
              ),
            if (server.isFavorite)
              Icon(
                Icons.star,
                color: Colors.amber.shade700,
                size: 20,
              ),
            IconButton(
              icon: const Icon(Icons.more_vert),
              onPressed: () {
                _showServerMenu(context, server);
              },
            ),
          ],
        ),
        onTap: () async {
          if (vpnProvider.status == VpnStatus.disconnected) {
            // 未连接状态，直接连接
            try {
              await vpnProvider.connect(server);
            } catch (e) {
              if (context.mounted) {
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('Failed to connect: $e')),
                );
              }
            }
          } else if (isCurrentServer) {
            // 点击当前连接的节点，断开连接
            await vpnProvider.disconnect();
          } else {
            // 已连接其他节点，弹出确认框询问是否切换
            _showSwitchConfirmDialog(context, vpnProvider, server);
          }
        },
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  IconData _getProtocolIcon(String protocol) {
    switch (protocol.toLowerCase()) {
      case 'vmess':
        return Icons.security;
      case 'vless':
        return Icons.shield;
      case 'trojan':
        return Icons.vpn_lock;
      case 'shadowsocks':
        return Icons.vpn_key;
      default:
        return Icons.dns;
    }
  }

  // 根据分组名称获取颜色
  Color _getGroupColor(String group) {
    final colors = [
      Colors.blue,
      Colors.green,
      Colors.orange,
      Colors.purple,
      Colors.red,
      Colors.teal,
      Colors.indigo,
      Colors.pink,
    ];
    
    // 使用分组名称的哈希值选择颜色
    final hash = group.hashCode.abs();
    return colors[hash % colors.length];
  }

  void _showServerMenu(BuildContext context, ServerConfig server) {
    final vpnProvider = Provider.of<VpnProvider>(context, listen: false);

    showModalBottomSheet(
      context: context,
      builder: (context) => SafeArea(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: Icon(
                server.isPinned ? Icons.push_pin : Icons.push_pin_outlined,
                color: server.isPinned ? Theme.of(context).colorScheme.primary : null,
              ),
              title: Text(
                server.isPinned ? 'Unpin from Top' : 'Pin to Top',
                style: TextStyle(
                  color: server.isPinned ? Theme.of(context).colorScheme.primary : null,
                  fontWeight: server.isPinned ? FontWeight.bold : null,
                ),
              ),
              onTap: () {
                vpnProvider.togglePin(server.id);
                Navigator.pop(context);
              },
            ),
            ListTile(
              leading: Icon(
                server.isFavorite ? Icons.star : Icons.star_border,
              ),
              title: Text(server.isFavorite ? 'Remove from Favorites' : 'Add to Favorites'),
              onTap: () {
                vpnProvider.toggleFavorite(server.id);
                Navigator.pop(context);
              },
            ),
            ListTile(
              leading: const Icon(Icons.speed),
              title: const Text('Test Ping'),
              onTap: () {
                Navigator.pop(context);
                showDialog(
                  context: context,
                  barrierDismissible: false,
                  builder: (context) => PingTestDialog(server: server),
                );
              },
            ),
            ListTile(
              leading: const Icon(Icons.edit),
              title: const Text('Edit'),
              onTap: () {
                Navigator.pop(context);
                showDialog(
                  context: context,
                  builder: (context) => EditServerDialog(server: server),
                );
              },
            ),
            ListTile(
              leading: const Icon(Icons.share),
              title: const Text('Share'),
              onTap: () {
                Navigator.pop(context);
                showDialog(
                  context: context,
                  builder: (context) => ShareConfigDialog(server: server),
                );
              },
            ),
            ListTile(
              leading: const Icon(Icons.delete),
              title: const Text('Delete'),
              onTap: () {
                Navigator.pop(context);
                _confirmDelete(context, server);
              },
            ),
          ],
        ),
      ),
    );
  }

  void _confirmDelete(BuildContext context, ServerConfig server) {
    final vpnProvider = Provider.of<VpnProvider>(context, listen: false);
    
    // 检查是否为当前连接的服务器（使用组合ID精确匹配）
    final isConnectedServer = vpnProvider.status == VpnStatus.connected && 
                              server.matchesServer(vpnProvider.currentServer);
    
    // 如果是正在连接的节点，不允许删除
    if (isConnectedServer) {
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: Row(
            children: [
              Icon(
                Icons.block,
                color: Colors.orange.shade700,
                size: 28,
              ),
              const SizedBox(width: 12),
              const Text('Cannot Delete'),
            ],
          ),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                'Cannot delete "${server.name}"',
                style: const TextStyle(
                  fontSize: 15,
                  fontWeight: FontWeight.w500,
                ),
              ),
              const SizedBox(height: 16),
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Theme.of(context).brightness == Brightness.dark
                      ? Colors.orange.shade900.withOpacity(0.2)
                      : Colors.orange.shade50,
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(
                    color: Theme.of(context).brightness == Brightness.dark
                        ? Colors.orange.shade700.withOpacity(0.5)
                        : Colors.orange.shade200,
                  ),
                ),
                child: Row(
                  children: [
                    Icon(
                      Icons.warning_amber_rounded,
                      color: Colors.orange.shade700,
                      size: 20,
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: Text(
                        'This server is currently connected. Please disconnect first before deleting.',
                        style: TextStyle(
                          fontSize: 13,
                          color: Theme.of(context).brightness == Brightness.dark
                              ? Colors.orange.shade300
                              : Colors.orange.shade900,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 12),
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Theme.of(context).brightness == Brightness.dark
                      ? Colors.blue.shade900.withOpacity(0.2)
                      : Colors.blue.shade50,
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Row(
                  children: [
                    Icon(
                      Icons.info_outline,
                      color: Colors.blue.shade700,
                      size: 20,
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: Text(
                        'Tip: Click on this server to disconnect, or tap the disconnect button on the home screen.',
                        style: TextStyle(
                          fontSize: 12,
                          color: Theme.of(context).brightness == Brightness.dark
                              ? Colors.blue.shade300
                              : Colors.blue.shade900,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('OK'),
            ),
          ],
        ),
      );
      return;
    }
    
    // 显示删除确认对话框
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Delete Server'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Are you sure you want to delete "${server.name}"?'),
            if (server.group != null && server.group!.isNotEmpty) ...[
              const SizedBox(height: 8),
              Text(
                'Group: ${server.group}',
                style: TextStyle(
                  fontSize: 13,
                  color: Theme.of(context).brightness == Brightness.dark
                      ? Colors.grey.shade400
                      : Colors.grey.shade600,
                ),
              ),
            ],
            if (server.remarks != null && server.remarks!.isNotEmpty) ...[
              const SizedBox(height: 4),
              Text(
                'Remarks: ${server.remarks}',
                style: TextStyle(
                  fontSize: 13,
                  color: Theme.of(context).brightness == Brightness.dark
                      ? Colors.grey.shade400
                      : Colors.grey.shade600,
                ),
              ),
            ],
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Cancel'),
          ),
          TextButton(
            onPressed: () {
              // 使用组合ID删除服务器
              _deleteServerByCompositeId(context, server);
              Navigator.pop(context);
            },
            child: const Text(
              'Delete',
              style: TextStyle(color: Colors.red),
            ),
          ),
        ],
      ),
    );
  }

  /// 通过组合ID删除服务器
  /// 确保精确匹配，避免误删同ID但不同分组/名称/备注的节点
  void _deleteServerByCompositeId(BuildContext context, ServerConfig server) {
    final vpnProvider = Provider.of<VpnProvider>(context, listen: false);
    
    // 查找所有服务器，找到组合ID匹配的节点
    final allServers = vpnProvider.allServers;
    final targetServer = allServers.firstWhere(
      (s) => s.matchesServer(server),
      orElse: () => server, // 如果找不到，使用原服务器（不应该发生）
    );
    
    // 删除找到的服务器
    vpnProvider.deleteServer(targetServer.id);
    
    // 显示成功消息
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Row(
          children: [
            const Icon(Icons.check_circle, color: Colors.white),
            const SizedBox(width: 12),
            Expanded(
              child: Text('Deleted "${server.name}"'),
            ),
          ],
        ),
        backgroundColor: Colors.green,
        duration: const Duration(seconds: 2),
      ),
    );
  }

  void _showSwitchConfirmDialog(
    BuildContext context,
    VpnProvider vpnProvider,
    ServerConfig newServer,
  ) {
    final currentServer = vpnProvider.currentServer;
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            Icon(
              Icons.swap_horiz,
              color: Theme.of(context).colorScheme.primary,
              size: 28,
            ),
            const SizedBox(width: 12),
            const Text('Switch Server?'),
          ],
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'You are currently connected to:',
              style: TextStyle(
                fontSize: 13,
                color: Colors.grey,
              ),
            ),
            const SizedBox(height: 8),
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Theme.of(context).brightness == Brightness.dark
                    ? Colors.red.shade900.withOpacity(0.2)
                    : Colors.red.shade50,
                borderRadius: BorderRadius.circular(8),
                border: Border.all(
                  color: Theme.of(context).brightness == Brightness.dark
                      ? Colors.red.shade700.withOpacity(0.5)
                      : Colors.red.shade200,
                  width: 1,
                ),
              ),
              child: Row(
                children: [
                  Icon(
                    Icons.link_off,
                    color: Colors.red.shade700,
                    size: 20,
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          currentServer?.name ?? 'Unknown',
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            color: Theme.of(context).brightness == Brightness.dark
                                ? Colors.red.shade300
                                : Colors.red.shade900,
                            fontSize: 14,
                          ),
                        ),
                        if (currentServer?.group != null) ...[
                          const SizedBox(height: 2),
                          Text(
                            'Group: ${currentServer!.group}',
                            style: TextStyle(
                              fontSize: 12,
                              color: Theme.of(context).brightness == Brightness.dark
                                  ? Colors.red.shade400
                                  : Colors.red.shade700,
                            ),
                          ),
                        ],
                      ],
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 16),
            const Text(
              'Switch to:',
              style: TextStyle(
                fontSize: 13,
                color: Colors.grey,
              ),
            ),
            const SizedBox(height: 8),
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Theme.of(context).brightness == Brightness.dark
                    ? Colors.green.shade900.withOpacity(0.2)
                    : Colors.green.shade50,
                borderRadius: BorderRadius.circular(8),
                border: Border.all(
                  color: Theme.of(context).brightness == Brightness.dark
                      ? Colors.green.shade700.withOpacity(0.5)
                      : Colors.green.shade200,
                  width: 1,
                ),
              ),
              child: Row(
                children: [
                  Icon(
                    Icons.link,
                    color: Colors.green.shade700,
                    size: 20,
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          newServer.name,
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            color: Theme.of(context).brightness == Brightness.dark
                                ? Colors.green.shade300
                                : Colors.green.shade900,
                            fontSize: 14,
                          ),
                        ),
                        if (newServer.group != null) ...[
                          const SizedBox(height: 2),
                          Text(
                            'Group: ${newServer.group}',
                            style: TextStyle(
                              fontSize: 12,
                              color: Theme.of(context).brightness == Brightness.dark
                                  ? Colors.green.shade400
                                  : Colors.green.shade700,
                            ),
                          ),
                        ],
                      ],
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 16),
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Theme.of(context).brightness == Brightness.dark
                    ? Colors.orange.shade900.withOpacity(0.2)
                    : Colors.orange.shade50,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Row(
                children: [
                  Icon(
                    Icons.info_outline,
                    color: Colors.orange.shade700,
                    size: 20,
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      'The current connection will be disconnected and reconnected to the new server.',
                      style: TextStyle(
                        fontSize: 12,
                        color: Theme.of(context).brightness == Brightness.dark
                            ? Colors.orange.shade300
                            : Colors.black87,
                        height: 1.4,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Cancel'),
          ),
          ElevatedButton.icon(
            onPressed: () async {
              Navigator.pop(context);
              
              // 显示切换中的提示
              if (context.mounted) {
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(
                    content: Row(
                      children: [
                        const SizedBox(
                          width: 16,
                          height: 16,
                          child: CircularProgressIndicator(
                            strokeWidth: 2,
                            valueColor: AlwaysStoppedAnimation(Colors.white),
                          ),
                        ),
                        const SizedBox(width: 12),
                        Text('Switching to ${newServer.name}...'),
                      ],
                    ),
                    duration: const Duration(seconds: 3),
                  ),
                );
              }
              
              // 先断开当前连接
              await vpnProvider.disconnect();
              
              // 等待一小段时间确保断开完成
              await Future.delayed(const Duration(milliseconds: 500));
              
              // 连接到新服务器
              try {
                await vpnProvider.connect(newServer);
                
                if (context.mounted) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(
                      content: Row(
                        children: [
                          Icon(
                            Icons.check_circle,
                            color: Colors.green.shade300,
                            size: 20,
                          ),
                          const SizedBox(width: 12),
                          Text('Switched to ${newServer.name}'),
                        ],
                      ),
                      backgroundColor: Colors.green.shade700,
                      duration: const Duration(seconds: 2),
                    ),
                  );
                }
              } catch (e) {
                if (context.mounted) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(
                      content: Row(
                        children: [
                          const Icon(
                            Icons.error_outline,
                            color: Colors.white,
                            size: 20,
                          ),
                          const SizedBox(width: 12),
                          Expanded(
                            child: Text('Failed to switch: $e'),
                          ),
                        ],
                      ),
                      backgroundColor: Colors.red,
                      duration: const Duration(seconds: 4),
                    ),
                  );
                }
              }
            },
            icon: const Icon(Icons.swap_horiz),
            label: const Text('Switch'),
            style: ElevatedButton.styleFrom(
              backgroundColor: Theme.of(context).colorScheme.primary,
              foregroundColor: Colors.white,
            ),
          ),
        ],
      ),
    );
  }
}
